package com.huizhonglm.diap.ui.user;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bruce.common.utils.EmptyUtil;
import com.bruce.common.utils.PatternUitl;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.model.user.AddrCreateParams;
import com.huizhonglm.diap.api.model.user.AddrInfo;
import com.huizhonglm.diap.api.model.user.AddrUpdateParams;
import com.huizhonglm.diap.core.storage.model.district.CityInfo;
import com.huizhonglm.diap.core.storage.model.district.DistInfo;
import com.huizhonglm.diap.core.storage.model.district.ProvInfo;
import com.huizhonglm.diap.core.utils.DialogUtil;
import com.huizhonglm.diap.core.utils.DistrictUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.model.District;
import com.huizhonglm.diap.presenters.user.AddrMgrPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.iView.AddrMgrIView;
import com.huizhonglm.diap.ui.views.CityPickerView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 *
 * @author LiXiaolong
 * @version 1.0
 * @since 2014年8月11日下午2:30:34
 */
public class AddrMgrActivity extends BaseActivity implements AddrMgrIView, View.OnClickListener,
        CityPickerView.OnDistrictSetListener {

    private Activity mContext;

    private EditText reciverNameEdt;
    private EditText phoneNumberEdt;
    private EditText postalCodeEdt;
    private EditText detailAddrEdt;
    private TextView locationTxt;
    private TextView deleteTxt;
    private View setDefLay;
    private View complateBtn;

    private CityPickerView cityPickView;


    private String provCode;
    private String cityCode;
    private String distCode;
    private String provName;
    private String cityName;
    private String distName;

    private AddrInfo mAddrInfo;

    private int resultCode = RESULT_CANCELED;

    private AddrMgrPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addr_mgr);
        setBackEvent(this, null);
        mContext = AddrMgrActivity.this;
        mPresenter = new AddrMgrPresenter(this);
        assignViews();
        initBundle();
    }

    @Override
    protected void assignViews() {
        reciverNameEdt = (EditText) findViewById(R.id.reciver_name_edt);
        phoneNumberEdt = (EditText) findViewById(R.id.phone_number_edt);
        postalCodeEdt = (EditText) findViewById(R.id.postal_code_edt);
        detailAddrEdt = (EditText) findViewById(R.id.detail_addr_edt);
        locationTxt = (TextView) findViewById(R.id.location_txt);
        deleteTxt = (TextView) findViewById(R.id.delete_addr_btn);
        setDefLay = findViewById(R.id.set_default_lay);
        complateBtn = findViewById(R.id.title_comp_txt);
        TextView setDefTxt = (TextView) findViewById(R.id.set_default_txt);

        reciverNameEdt.addTextChangedListener(new MyTextWatcher(reciverNameEdt));
        phoneNumberEdt.addTextChangedListener(new MyTextWatcher(phoneNumberEdt));
        postalCodeEdt.addTextChangedListener(new MyTextWatcher(postalCodeEdt));
        detailAddrEdt.addTextChangedListener(new MyTextWatcher(detailAddrEdt));
        locationTxt.addTextChangedListener(new MyTextWatcher(locationTxt));
        cityPickView = new CityPickerView(mContext, findViewById(R.id.my_addr_mgr_page), this);

        complateBtn.setOnClickListener(this);
        locationTxt.setOnClickListener(this);
        deleteTxt.setOnClickListener(this);
        setDefTxt.setOnClickListener(this);
        complateBtn.setEnabled(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_comp_txt:
                if (mAddrInfo == null) {
                    createAddr();
                } else {
                    updateAddr();
                }
                break;
            case R.id.location_txt:
                closeKeyboard(AddrMgrActivity.this);
                cityPickView.show(provName, cityName, distName);
                break;
            case R.id.delete_addr_btn:
                deleteAddr();
                break;
            case R.id.set_default_txt:
                if (mAddrInfo != null) {
                    showProgressBar();
                    mPresenter.setDefault(mAddrInfo.getAddrId(), UserUtil.getUserId());
                }
                break;
        }
    }

    private void initBundle(){
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mAddrInfo = (AddrInfo) bundle.getSerializable("addrInfo");
            if (mAddrInfo != null) {
                setValue();
            }
        }
    }

    private void setValue(){
        provCode = mAddrInfo.getProvCode();
        cityCode = mAddrInfo.getCityCode();
        distCode = mAddrInfo.getDistrictCode();
        deleteTxt.setVisibility(View.VISIBLE);
        setDefLay.setVisibility(View.VISIBLE);
        reciverNameEdt.setText(mAddrInfo.getReceiver());
        phoneNumberEdt.setText(mAddrInfo.getPhoneNum());
        postalCodeEdt.setText(mAddrInfo.getPostCode());
        detailAddrEdt.setText(mAddrInfo.getDetailAddr());
        District dist = DistrictUtil.getInstance().getDistrict(mAddrInfo.getDistrictCode());
        provName = dist.getProvName();
        cityName = dist.getCityName();
        distName = dist.getDistName();
        locationTxt.setText(getLocation(provName, cityName, distName));
    }

    private void createAddr(){
        if (checkData()) {
            showProgressBar();
            String reciverName = reciverNameEdt.getText().toString();
            String phoneNumber = phoneNumberEdt.getText().toString();
            String postalCode = postalCodeEdt.getText().toString();
            String detailAddr = detailAddrEdt.getText().toString();
            AddrCreateParams params = new AddrCreateParams();
            params.userId = UserUtil.getUserId();
            params.receiver = reciverName;
            params.phoneNumber = phoneNumber;
            params.postCode = postalCode;
            params.detailAddr = detailAddr;
            params.provCode = provCode;
            params.cityCode = cityCode;
            params.districtCode = distCode;
            mPresenter.createAddr(params);
        }
    }

    private void updateAddr(){
        if (checkData()) {
            showProgressBar();
            String reciverName = reciverNameEdt.getText().toString();
            String phoneNumber = phoneNumberEdt.getText().toString();
            String postalCode = postalCodeEdt.getText().toString();
            String detailAddr = detailAddrEdt.getText().toString();

            AddrUpdateParams params = new AddrUpdateParams();
            params.addrId = mAddrInfo.getAddrId();
            params.receiver = reciverName;
            params.phoneNumber = phoneNumber;
            params.postCode = postalCode;
            params.detailAddr = detailAddr;
            params.provCode = provCode;
            params.cityCode = cityCode;
            params.districtCode = distCode;
            mPresenter.updateAddr(params);
        }
    }

    private void deleteAddr(){
        DialogUtil.showNormalDialog(this,"删除提示", "您确定要删除此收货地址吗？", "取消", "确定", new DialogUtil.OnDialogBtnClickListener() {
            @Override
            public void onBtnClick(String btnText) {
                if ("确定".equals(btnText)) {
                    showProgressBar();
                    mPresenter.deleteAddr(mAddrInfo.getAddrId());
                }
            }
        });
    }

    private boolean checkData(){
        String reciverName = reciverNameEdt.getText().toString();
        String phoneNumber = phoneNumberEdt.getText().toString();
        String postalCode = postalCodeEdt.getText().toString();
        String detailAddr = detailAddrEdt.getText().toString();
        if (EmptyUtil.isEmpty(reciverName)) {
            ToastUtil.makeTextShort("请输入收件人姓名");
            return false;
        }
        if (EmptyUtil.isEmpty(phoneNumber)) {
            ToastUtil.makeTextShort("请输入手机号码");
            return false;
        } else {
            if (phoneNumber.length() != 11 && !PatternUitl.isPhone(phoneNumber)) {
                ToastUtil.makeTextShort("手机号码格式有误");
                return false;
            }
        }
        if (EmptyUtil.isEmpty(postalCode)) {
            ToastUtil.makeTextShort("请输入邮政编码");
            return false;
        }
        if (EmptyUtil.isEmpty(provCode) || EmptyUtil.isEmpty(cityCode) || EmptyUtil.isEmpty(distCode)) {
            ToastUtil.makeTextShort("请选择所在地区");
            return false;
        }
        if (EmptyUtil.isEmpty(detailAddr)) {
            ToastUtil.makeTextShort("请输入详细地址");
            return false;
        }
        return true;
    }

    private String getLocation(String pName, String cName, String dName){
        StringBuilder builder = new StringBuilder();
        switch (pName) {
            case "北京":
            case "上海":
            case "天津":
            case "重庆":
                builder.append(cName);
                break;
            case "台湾":
            case "香港":
            case "澳门":
                builder.append(pName).append("  ").append(cName);
                break;
            default:
                builder.append(pName).append("省").append("  ").append(cName);
                break;
        }
        builder.append("  ").append(dName);
        return builder.toString();
    }

    @Override
    public void onDistrictSet(ProvInfo prov, CityInfo city, DistInfo dist) {
        provName = prov.getProvName();
        cityName = city.getCityName();
        distName = dist.getDistName();
        locationTxt.setText(getLocation(provName, cityName, distName));
        provCode = prov.getProvId();
        cityCode = city.getCityCode();
        distCode = dist.getDistId();
    }

    @Override
    public void createSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址添加成功");
        resultCode = RESULT_OK;
        onFinish();
    }

    @Override
    public void createFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址添加失败，请稍后重试");
    }

    @Override
    public void updateSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址修改成功");
        resultCode = RESULT_OK;
        onFinish();
    }

    @Override
    public void updateFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址修改失败，请稍后重试");
    }

    @Override
    public void deleteSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址删除成功");
        resultCode = RESULT_OK;
        onFinish();
    }

    @Override
    public void deleteFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("地址删除失败，请稍后重试");
    }

    @Override
    public void defaultSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("设置默认地址成功");
        resultCode = RESULT_OK;
        onFinish();
    }

    @Override
    public void defaultFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("设置默认地址失败，请稍后重试");
    }

    @Override
    public void onBackPressed() {
        onFinish();
    }

    private void onFinish(){
        setResult(resultCode);
        finish();
    }

    public class MyTextWatcher implements TextWatcher{

        private TextView mEditText;

        public MyTextWatcher(TextView edt) {
            this.mEditText = edt;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mEditText.equals(reciverNameEdt)) {
                String source = reciverNameEdt.getText().toString();
                String regEx = "[\\n]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(source);
                String text = m.replaceAll("");
                if (!source.equals(text)) {
                    reciverNameEdt.setText(text);
                    reciverNameEdt.setSelection(text.length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            Editable name = reciverNameEdt.getText();
            Editable phone = phoneNumberEdt.getText();
            Editable postal = postalCodeEdt.getText();
            CharSequence dist = locationTxt.getText();
            Editable detail = detailAddrEdt.getText();
            if ((name != null && name.length() > 0) ||
                    (phone != null && phone.length() > 0) ||
                    (postal != null && postal.length() > 0) ||
                    (dist != null && dist.length() > 0) ||
                    (detail != null && detail.length() > 0)) {
                complateBtn.setEnabled(true);
            } else {
                complateBtn.setEnabled(false);
            }
        }
    }
}
